package com.laizhenghua.hotel.controller;

import com.alibaba.fastjson.JSON;
import com.laizhenghua.hotel.entity.UsersEntity;
import com.laizhenghua.hotel.service.CatesService;
import com.laizhenghua.hotel.utils.R;
import com.laizhenghua.hotel.vo.CatesVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @description: 处理首页请求
 * @author: laizhenghua
 * @date: 2021/3/12 13:12
 */
@Controller
@RequestMapping(path = "/app")
public class HomeController {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private CatesService catesService;

    @GetMapping(path = {"/index","/index.html"})
    public String index(){
        // System.out.println("进入首页");
        return "app/index";
    }
    @GetMapping("/category.json")
    @ResponseBody
    public R getCategory(){
        List<CatesVo> catesVos = catesService.getByPid(0);
        // System.out.println(getChild(catesVos));
        return R.ok().put("cates",getChild(catesVos));
    }
    /**
     * 递归获取子菜单
     */
    public List<CatesVo> getChild(List<CatesVo> list) {
        if(list != null && list.size() > 0){
            for(CatesVo category : list){
                List<CatesVo> subList = catesService.getByPid(category.getId());
                category.setSubs(getChild(subList));
            }
        }
        return list;
    }

    /**
     * 首页用户信息展示
     * API：http://localhost:8080/app/index/{user.id}
     */
    @GetMapping("/index/{user_id}")
    public String getUserInfo(@PathVariable("user_id") Integer user_id, Model model){
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        UsersEntity usersEntity = (UsersEntity) ops.get("user_" + user_id);
        model.addAttribute("user_info",usersEntity);
        return "app/index";
    }
}
